import json
import time
from pathlib import Path
from typing import Any


# { code=14 security=123456 msg="tid=zhaoyangkun wife=chengwenfang" }
def parse_apf_str(msg):
    body_info_dict = {}
    key = ""
    val = ""
    is_double_quote = False
    key_scope = False
    val_scope = False
    for i in range(len(msg)):
        if msg[i] in ("{", "}"):
            continue
        elif not is_double_quote and i >= 1 and msg[i] != " " and msg[i - 1] == " ":
            key_scope = True
            key += msg[i]
        elif not is_double_quote and msg[i] == "=":
            if msg[i + 1] == '"':
                is_double_quote = True
            key_scope = False
            val_scope = True
        elif (
            not is_double_quote and msg[i] == " " and msg[i - 1] not in (" ", "{")
        ) or (is_double_quote and msg[i] == " " and msg[i - 1] == '"'):
            body_info_dict[key] = val
            key = ""
            val = ""
            key_scope = False
            val_scope = False
            is_double_quote = False
        elif key_scope and not val_scope:
            key += msg[i]
        elif val_scope and not key_scope:
            val += msg[i]
        else:
            continue
    return body_info_dict


def save_json_data(dict_data: dict[str, Any], save_path: str | Path):
    json_data = json.dumps(dict_data, indent=4, ensure_ascii=False)
    print(json_data)
    json_file = Path(save_path)
    json_file.touch(exist_ok=True)
    with open(json_file, "w") as f:
        f.write(json_data)


if __name__ == "__main__":
    start_time = time.perf_counter()
    dict_data = parse_apf_str(
        '{ code=14 security=123456 msg="tid=zhaoyangkun wife=chengwenfang" }'
    )
    save_json_data(dict_data=dict_data, save_path="./parse.json")
    end_time = time.perf_counter()
    print(f"time: {end_time - start_time:.4f}s")
